﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Public;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.ProjectFrom
{
    /// <summary>
    /// 弹出项目维护列表窗体
    /// </summary>
    public partial class ProjectMaintenanceSelectForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectMaintenanceSelectForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 存储已选中的项目维护数据列表
        /// </summary>
        private List<ProjectMaintenanceOutput> selectedItems = new List<ProjectMaintenanceOutput>();

        /// <summary>
        /// 用于显示已选择项目数量的标签控件
        /// </summary>
        private DevExpress.XtraEditors.LabelControl labelSelectedCount;

        /// <summary>
        /// 定义委托，用于将选中的数据传回调用窗体
        /// </summary>
        public delegate void ProjectMaintenanceSelectedHandler(List<ProjectMaintenanceOutput> selectedItems);

        /// <summary>
        /// 定义事件，当确认选择时触发
        /// </summary>
        public event ProjectMaintenanceSelectedHandler OnProjectMaintenanceSelected;

        private int pageIndex = 1; // 当前页码
        private int pageSize = 3; // 每页显示的记录数
        private int totalCount = 0; // 总记录数
        private int totalPages = 0;// 总页数

        /// <summary>
        /// 获取项目维护列表并刷新
        /// </summary>
        /// <returns></returns>
        private async Task ReInit(string projectMaintenanceCode = "", string projectMaintenanceName = "")
        {
            List<ProjectMaintenanceOutput> projectMaintenanceOutputs = new List<ProjectMaintenanceOutput>();
            // 修复原有的逻辑错误：根据条件决定调用哪个方法获取数据
            if (!string.IsNullOrEmpty(projectMaintenanceCode) || !string.IsNullOrEmpty(projectMaintenanceName))
            {
                // 有查询条件时，使用条件查询
                projectMaintenanceOutputs = await GetProjectMaintenanceByCondition(projectMaintenanceCode, projectMaintenanceName);
            }
            else
            {
                // 无查询条件时，获取所有数据
                projectMaintenanceOutputs = await GetProjectMaintenanceList();
            }
            // 设置数据源
            gridControl1.DataSource = projectMaintenanceOutputs;
            // 获取GridView对象
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                gridView.Columns.Clear();

                // 1. 设置GridView允许多选
                gridView.OptionsSelection.MultiSelect = true;

                // 2. 设置多选模式为复选框
                gridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

                // 3. 在列头显示复选框（全选/取消全选功能）
                gridView.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.True;
                gridView.Columns.AddVisible("Id", "编号");
                gridView.Columns.AddVisible("ProjectMaintenanceCode", "项目维护编码");
                gridView.Columns.AddVisible("ProjectMaintenanceName", "项目维护名称");
                //gridView.Columns.AddVisible("CheckoutWay", "检出方式");
                gridView.Columns.AddVisible("CheckoutWayText", "检出方式");

                // 绑定选择变更事件（先移除再添加，避免重复绑定）
                gridView.SelectionChanged -= GridView_SelectionChanged;
                gridView.SelectionChanged += GridView_SelectionChanged;

                // 预选已选中的项目
                if (selectedItems.Count > 0)
                {
                    PreSelectItems(gridView);
                }

                // 更新已选择数量显示
                //UpdateSelectedCountLabel();
            }
        }

        /// <summary>
        /// 选择变更事件处理 - 当用户选中或取消选中行时触发
        /// </summary>
        private void GridView_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            try
            {
                var gridView = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                if (gridView != null)
                {
                    // 清空已选择项目列表
                    selectedItems.Clear();

                    // 获取所有选中行的行号
                    int[] selectedRows = gridView.GetSelectedRows();

                    // 遍历所有选中行
                    foreach (int rowHandle in selectedRows)
                    {
                        // 确保行号有效
                        if (rowHandle >= 0)
                        {
                            // 获取行对应的数据对象
                            var item = gridView.GetRow(rowHandle) as ProjectMaintenanceOutput;
                            if (item != null)
                            {
                                // 将选中的项目添加到列表中
                                selectedItems.Add(item);
                            }
                        }
                    }

                    // 更新已选择数量显示
                    //UpdateSelectedCountLabel();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"选择操作出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新已选择数量标签
        /// </summary>
        //private void UpdateSelectedCountLabel()
        //{
        //    try
        //    {
        //        // 如果标签控件不存在，则创建它
        //        if (labelSelectedCount == null)
        //        {
        //            labelSelectedCount = new DevExpress.XtraEditors.LabelControl();
        //            labelSelectedCount.Parent = this.panelControl1; // 放在顶部面板中
        //            labelSelectedCount.Location = new System.Drawing.Point(20, 20); // 位置可根据实际布局调整
        //            labelSelectedCount.AutoSize = true;
        //            labelSelectedCount.Visible = true;
        //            this.panelControl1.Controls.Add(labelSelectedCount);
        //        }

        //        // 更新标签文本，显示已选择的数量
        //        labelSelectedCount.Text = $"已选择{selectedItems.Count}项(可跨页)";
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"更新选择数量标签出错：{ex.Message}");
        //    }
        //}

        /// <summary>
        /// 预选已选中的项目
        /// </summary>
        private void PreSelectItems(DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {
            try
            {
                if (gridView != null && selectedItems.Count > 0)
                {
                    // 开始批量选择操作
                    gridView.BeginSelection();

                    try
                    {
                        // 遍历所有行
                        for (int i = 0; i < gridView.RowCount; i++)
                        {
                            // 获取行数据
                            var row = gridView.GetRow(i) as ProjectMaintenanceOutput;

                            // 如果当前行在已选择列表中，则选中该行
                            if (row != null && selectedItems.Any(s => s.Id == row.Id))
                            {
                                gridView.SelectRow(i);
                            }
                        }
                    }
                    finally
                    {
                        // 结束批量选择操作
                        gridView.EndSelection();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"预选项目出错：{ex.Message}");
            }
        }

        /// <summary>
        /// 设置预选项目 - 供外部调用，预先选中指定的项目
        /// </summary>
        public void SetPreSelectedItems(List<ProjectMaintenanceOutput> items)
        {
            try
            {
                if (items != null && items.Count > 0)
                {
                    // 复制传入的列表，避免引用问题
                    selectedItems = new List<ProjectMaintenanceOutput>(items);

                    // 更新已选择数量显示
                    //UpdateSelectedCountLabel();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"设置预选项目时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新项目维护列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private async void ProjectMaintenanceSelectForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 初始化已选择数量标签
                //UpdateSelectedCountLabel();

                // 加载数据
                await ReInit();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"窗体加载时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取项目维护列表
        /// </summary>
        /// <returns></returns>
        private async Task<List<ProjectMaintenanceOutput>> GetProjectMaintenanceList()
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStringAsync("http://localhost:5229/api/ProjectMaintenance/GetProjectMaintenanceList");
                var result = JsonConvert.DeserializeObject<ApiPaging<ProjectMaintenanceOutput>>(response);
                totalCount = result.TotalCount;
                totalPages = (int)Math.Ceiling((totalCount * 1.0) / pageSize);
                return result.PageData;
            }
        }

        /// <summary>
        /// 根据条件获取项目维护列表
        /// </summary>
        /// <param name="projectMaintenanceCode"></param>
        /// <param name="projectMaintenanceName"></param>
        /// <param name="criterion"></param>
        private async Task<List<ProjectMaintenanceOutput>> GetProjectMaintenanceByCondition(string projectMaintenanceCode, string projectMaintenanceName)
        {
            try
            {
                using (var clien = new HttpClient())
                {
                    // 构造查询参数字符串，包含分页参数
                    string queryParams = $"PageIndex={pageIndex}&PageSize={pageSize}";
                    // 如果有条件，则添加条件查询参数

                    if (!string.IsNullOrEmpty(projectMaintenanceCode))
                    {
                        queryParams += $"&ProjectMaintenanceCode={projectMaintenanceCode}";
                    }

                    if (!string.IsNullOrEmpty(projectMaintenanceName))
                    {
                        queryParams += $"&ProjectMaintenanceName={projectMaintenanceName}";
                    }

                    var response = await clien.GetStringAsync($"http://localhost:5229/api/ProjectMaintenance/GetProjectMaintenanceList?{queryParams}");
                    return JsonConvert.DeserializeObject<ApiPaging<ProjectMaintenanceOutput>>(response).PageData;

                }
            }
            catch (Exception ex)
            {
                // 查询过程中发生异常，弹窗提示错误信息，并返回空列表
                MessageBox.Show($"查询出错：{ex.Message}");
                return new List<ProjectMaintenanceOutput>();
            }
        }

        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void QueryButton2_Click(object sender, EventArgs e)
        {
            // 获取查询条件
            string projectMaintenanceCode = ProjectMaintenanceCode.Text.Trim();
            string projectMaintenanceName = ProjectMaintenanceName.Text.Trim();
            await ReInit(projectMaintenanceCode, projectMaintenanceName);

            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                //提示查询到的数量
                var totalCount = gridView.DataRowCount;
                XtraMessageBox.Show($"查询到{totalCount}条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResetButton3_Click(object sender, EventArgs e)
        {
            ProjectMaintenanceCode.Text = "";
            ProjectMaintenanceName.Text = "";
        }

        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PrevPageButton5_Click(object sender, EventArgs e)
        {
            if (pageIndex <= 1)
            {
                XtraMessageBox.Show("已经是第一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            pageIndex -= 1;
            await ReInit();
        }

        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void NextPageButton4_Click(object sender, EventArgs e)
        {
            if (pageIndex >= totalPages)
            {
                XtraMessageBox.Show("已经是最后一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            pageIndex += 1;
            await ReInit();
        }

        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SureButton6_Click(object sender, EventArgs e)
        {
            try
            {
                // 触发选择完成事件，将选中的项目传递给调用窗体
                if (OnProjectMaintenanceSelected != null)
                {
                    OnProjectMaintenanceSelected(selectedItems);
                }

                // 设置对话框结果为OK，并关闭窗体
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"确认选择时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 设置对话框结果为Cancel，并关闭窗体
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"取消操作时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

}